package com.cntaiping.ttnews.adapter;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.ZoomButtonsController;

import com.cntaiping.ttnews.R;
import com.cntaiping.ttnews.bean.VideoDataBean;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/7/21.
 */
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoHolder> implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {
    private String TAG = "VideoAdapter";
    private List<VideoDataBean.NewslistBean> mList;
    private List<VideoDataBean.ChangeInfoBean.SubIdCommentsBean> commentList;
    private VideoDataBean.ChangeInfoBean changeInfoBean;
    private Context mContext;
    private VideoDataBean mBean;
    private MediaPlayer mMediaPlayer;

    public VideoAdapter(Context context, VideoDataBean bean) {
        this.mContext = context;
        mBean =bean;
        mList = new ArrayList<>();
    }

    @Override
    public VideoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final View itemView = LayoutInflater.from(mContext).inflate(R.layout.item_video, parent, false);
        Log.i(TAG,"执行几次？？ ");
        return new VideoHolder(itemView, new PlayVideoListener() {
            @Override
            public void playVideo(View view, int position) {
                //
                final SurfaceView surfaceView = (SurfaceView) itemView.findViewById(R.id.vv_video);
                String videoPath =  mList.get(position).getVideo_channel().getVideo().getPlayurl();
                Log.i(TAG, "playVideo: -------视频地址-----" + videoPath);
                toPlay(surfaceView , videoPath);
            }

        });
    }

    @Override
    public void onBindViewHolder( VideoHolder holder, final int position) {

        DecimalFormat df1 = new DecimalFormat("##0.00");
        DecimalFormat df   = new DecimalFormat("######0.00");
        String result = String.format("3.1415926" , "%.2f");
        String string = df.format(3.1415926);
        Log.i(TAG, "2位小数: ---！！！！----"+string);
        Log.i(TAG, "onBindViewHolder: ---1----"+position);
        double count = mList.get(position).getVideo_channel().getVideo().getPlaycount() / 10000.0;
        String playcount = df.format(count);
        String duration = mList.get(position).getVideo_channel().getVideo().getDuration();
      //  Picasso.with(mContext).load(mList.get(position).getVideo_channel().getVideo().getImg()).resize(320, 200).into(holder.iv_video);
        holder.tv_title.setText(mList.get(position).getTitle());
        holder.tv_duration.setText(playcount + "万播放/" + duration);
        holder.tv_source.setText(mList.get(position).getSource());
        holder.tv_comments.setText(changeInfoBean.getSubIdComments().get(position).getComments()+"");

        //点击列表中的条目，如果焦点在video上播放视频，如果在下面linearLayout上，则跳转
        holder.ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.llClick(v , position);
            }
        });
    }


    @Override
    public int getItemCount() {
        Log.i(TAG, "getItemCount: ---2---"+mList.size());
        return mList == null ? 0 : mList.size();

    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mMediaPlayer.start();
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {

    }

    public class VideoHolder extends RecyclerView.ViewHolder {
        private TextView tv_title, tv_source, tv_duration, tv_comments;
        private ImageView iv_video;
        private LinearLayout ll;
        private SurfaceView vv;
        private CardView card;
        private PlayVideoListener playListener;
        public VideoHolder(View itemView , PlayVideoListener listener) {
            super(itemView);
            tv_title = (TextView) itemView.findViewById(R.id.tv_title);
            tv_source = (TextView) itemView.findViewById(R.id.tv_source);
            tv_duration = (TextView) itemView.findViewById(R.id.tv_count_duration);
            tv_comments = (TextView) itemView.findViewById(R.id.tv_comments);
           // iv_video = (ImageView) itemView.findViewById(R.id.iv_video);
            ll = (LinearLayout) itemView.findViewById(R.id.ll_line);
            vv = (SurfaceView) itemView.findViewById(R.id.vv_video);
            card = (CardView) itemView.findViewById(R.id.card_video);
            playListener = listener;
            card.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    playListener.playVideo(v , getLayoutPosition());
                }
            });
        }

    }
    public void dataChange(VideoDataBean bean){
        mList = bean.getNewslist();
        changeInfoBean = bean.getChangeInfo();
        notifyDataSetChanged();
    }

    //单项监听
    private OnVideoClickListener mListener;
    public void setOnVideoClickListener(OnVideoClickListener listener){
        this.mListener = listener;
    }
    public interface OnVideoClickListener{
      //  void videoClick(View view , int position);
        void llClick(View view , int position);
    }

    //内部videoview监听
    public interface PlayVideoListener{
        void playVideo(View view , int position);
    }

    //使用surfaceView
    public void toPlay(SurfaceView surfaceView , final String path){
        mMediaPlayer = new MediaPlayer();
        //surfaceView的管理类
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        //添加声明周期的接口回调
        surfaceHolder.addCallback(new SurfaceHolder.Callback() {
            //surface创建完成时候。在这里做一些初始化的设置
            //比如，设置视频的显示，设置视频源。。
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                mMediaPlayer.setDisplay(holder);

                try {
                    //得到asset目录下的音频文件
                   // AssetFileDescriptor assetFileDescriptor = mContext.getAssets().openFd("shabc.mp4");
                    //设置数据源
                   // mMediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                   mMediaPlayer.setDataSource(path);
                    mMediaPlayer.prepareAsync();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //surface内部改变的时候回调用此方法
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            //surface销毁时候
            //释放资源的操作，在这里执行。
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (mMediaPlayer != null) {
                    mMediaPlayer.pause();
                    mMediaPlayer.release();
                    mMediaPlayer = null;
                }
            }
        });
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnCompletionListener(this);

        surfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //MotionEvent交给手势探测类GestureDetector类来处理
                mDetector.onTouchEvent(event);
                return true;
            }
        });
    }

    GestureDetector mDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
        //        //单击的回调
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            Log.i("tag", "点击了。");


            return super.onSingleTapUp(e);
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            Log.i("tag", "双击。。。");
            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                mMediaPlayer.pause();
            } else if (mMediaPlayer != null) {
                mMediaPlayer.start();
            }
            return super.onDoubleTap(e);
        }
    });
}
